import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:densefog/const.dart';
import 'package:densefog/utils.dart';

final _paint = Paint();
const _radius = Radius.circular(borderRadius);

class BoardCellPainter extends CustomPainter {
  final Color fieldCellColor;
  final Color borderColor;

  const BoardCellPainter({
    required this.fieldCellColor,
    required this.borderColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final offsetWH = size.width / cellCount;

    _paint.color = fieldCellColor;
    _paint.style = PaintingStyle.fill;

    const padding = cellCount * 7.5;

    for (var i = 0; i < cellCount + 1; i++) {
      for (var j = 0; j < cellCount; j++) {
        final top = offsetWH * i + padding;
        final left = offsetWH * j + padding;

        final right = offsetWH * j + offsetWH - padding;
        final bottom = offsetWH * i + offsetWH - padding;

        final rRect = RRect.fromLTRBR(left, top, right, bottom, _radius);
        canvas.drawRRect(
          rRect,
          _paint,
        );
      }
    }

    const offset = 12.0;
    final rect = RRect.fromLTRBR(
      -offset,
      -offset,
      size.width + offset,
      size.width + cellSize + offset,
      const Radius.circular(20.0),
    );

    final linePaint = Paint();
    linePaint.strokeWidth = 6.0;
    linePaint.style = PaintingStyle.stroke;
    linePaint.color = borderColor;

    final cRect = Rect.fromLTWH(
      cellSize,
      rect.bottom - linePaint.strokeWidth,
      cellSize * 2,
      linePaint.strokeWidth * 3,
    );

    canvas.clipRect(
      cRect,
      clipOp: ClipOp.difference,
    );

    final pa = Path()
      ..addRRect(rect.shift(const Offset(0, 4)))
      ..addRRect(rect)
      ..fillType = PathFillType.evenOdd;

    final shPaint = Paint()
      ..color = Colors.black12
      ..maskFilter = MaskFilter.blur(
        BlurStyle.normal,
        convertRadiusToSigma(3),
      );

    canvas.drawPath(pa, shPaint);

    final path = Path();
    path.addRRect(rect);
    canvas.drawPath(path, linePaint);
  }

  @override
  bool shouldRepaint(BoardCellPainter oldDelegate) =>
      fieldCellColor != oldDelegate.fieldCellColor;
}
